package com.hongye.customer.web;

import com.alipay.api.internal.util.AlipaySignature;
import com.hongye.customer.config.AlipayTemplate;
import com.hongye.customer.service.OrderService;
import com.hongye.customer.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
    凤兮凤兮归故乡，遨游千里求其凰
    2021/6/18
*/
@Slf4j
@RestController
@RequestMapping("/user/pay")
public class PayWebController {

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private OrderService orderService;

    @Value("${alipay.alipay_public_key}")
    private String alipay_public_key;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.sign_type}")
    private String sign_type;

    @RequestMapping(value = "/payOrder",produces = "text/html")
    public String payOrder(@RequestParam("orderId") String orderId) throws Exception {
        PayVo payVo = orderService.getOrderById(orderId);
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }

    /**
     * 消息回调
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/return")
    public String ret(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝 流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //去修改订单状态
            //String result = orderService.handlePayResult(asyncVo);
            log.info("签名验证成功...:"+"out_trade_no:"+out_trade_no+",trade_no:"+trade_no+",total_amount:"+total_amount);
            String result = orderService.updateOrderStatus(out_trade_no,trade_no,total_amount);
            return result;
        } else {
            log.info("签名验证失败...");
            return "error";
        }
    }

}
